<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactMessageBatchSend\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Rbac\Contract\RbacRoleContract;
use MoChat\App\Rbac\Contract\RbacUserRoleContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 客户消息群发 - 员工权限.
 * @Controller
 */
class EmployeeInfo extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var RbacUserRoleContract
     */
    protected $rbacUserRoleService;

    /**
     * @Inject
     * @var RbacRoleContract
     */
    protected $rbacRoleService;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/contactMessageBatchSend/employeeInfo", methods="get")
     */
    public function handle(): array
    {
        // 接收参数
        $user = user();
        $params['corpId'] = (int) $user['corpId'];
        $params['employeeId'] = (int) $user['id'];
        $corpId = (int) $user['corpId'];

        if (empty($user) || empty($user['logUserId'])) {
            return ['employeeId' => 0, 'permissionType' => 2];
        }
        $userRole = $this->rbacUserRoleService->getRbacUserRoleByUserId($user['logUserId'], ['role_id']);
        if (empty($userRole)) {
            return ['employeeId' => $user['id'], 'permissionType' => 2];
        }
        $role = $this->rbacRoleService->getRbacRoleById($userRole['roleId'], ['data_permission']);
        if (empty($role) || empty($role['dataPermission'])) {
            return ['employeeId' => $user['id'], 'permissionType' => 2];
        }
        foreach (Json::decode($role['dataPermission']) as $item) {
            if ($item['corpId'] === $corpId) {
                return ['employeeId' => $user['id'], 'permissionType' => $item['permissionType']];
            }
        }
        return ['employeeId' => $user['id'], 'permissionType' => 2];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [];
    }
}
